//
//  WebViewController.swift
//  SwiftCode
//
//  Created by yuhus on 2024/3/27.
//

import Foundation
import WebKit

public struct WebParam: SinkEntity {
  public let url: URL
  
  public let title: String
  
  /// 是否显示标题 true 代表使用Android的, false代表不用 Android的 title
  public let showTitle: Bool
  
  /// 是否透明顶部 true代表使用web的, false 代表使用 Android 的
  public let isTranTop: Bool
}

class WebViewController: BaseViewController {
  private let args: WebParam
  
  init(_ args: WebParam) {
    self.args = args
    Timber.d(args)
    super.init(nibName: nil, bundle: nil)
  }
  
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    if args.showTitle {
      navigationItem.titleView = createTitleView(args.title)
    }
    
    view.addSubview(webView)
    webView.snp.makeConstraints { make in
      if args.isTranTop {
        make.top.equalToSuperview()
      } else {
        make.top.equalTo(view.safeAreaLayoutGuide)
      }
      make.leading.trailing.bottom.equalToSuperview()
    }
    
    let request = URLRequest(url: args.url)
    webView.load(request)
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if args.isTranTop {
      navigationController?.setNavigationBarHidden(true, animated: false)
    }
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    if args.isTranTop {
      navigationController?.setNavigationBarHidden(false, animated: false)
    }
  }
  
  private lazy var webView: WKWebView = {
    let webView = WKWebView(frame: .zero, configuration: configuration)
    if args.isTranTop {
      webView.scrollView.contentInsetAdjustmentBehavior = .never
    }
    return webView
  }()
  
  // 禁用webview默认的长按手势选项菜单
  lazy var configuration: WKWebViewConfiguration = {
    var javascript = String()
    // 禁止长按
    javascript.append("document.documentElement.style.webkitTouchCallout='none';")
    // 禁止选择
    javascript.append("document.documentElement.style.webkitUserSelect='none';")
    // 禁止缩放
    javascript.append("var meta = document.createElement('meta');")
    javascript.append("meta.setAttribute('name', 'viewport');")
    javascript.append("meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');")
    javascript.append("document.getElementsByTagName('head')[0].appendChild(meta);")
    let noneSelectScript = WKUserScript(source: javascript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
    let userContentController = WKUserContentController()
    userContentController.addUserScript(noneSelectScript)
    let configuration = WKWebViewConfiguration()
    configuration.userContentController = userContentController
    return configuration
  }()
}
